﻿using System;
using System.IO;
using System.ServiceModel.Activation;
using System.Text;
using System.Web;
using System.Web.Routing;

namespace TestWcfRestService
{
    public class Global : HttpApplication
    {
        const string TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
        const string TIME_FILE_FORMAT = "yyyy-MM-dd HH-mm-ss";

        void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes();
        }

        private void RegisterRoutes()
        {
            RouteTable.Routes.Add(new ServiceRoute("Service1", new WebServiceHostFactory(), typeof(Service1)));
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            var request = HttpContext.Current.Request;
            var logContent = new StringBuilder(2 * 1024); //default capacity 2kb
            try
            {
                if (null != request)
                {
                    logContent.Append("Request = ");

                    var sRequestTime = "UTC " + DateTime.UtcNow.ToString(TIME_FORMAT);
                    var requestJson = HttpHelper.GetRequestJson(request, sRequestTime);
                    var formattedRequestJson = JsonHelper.FormatJson(requestJson);
                    logContent.AppendLine(formattedRequestJson);
                }

                HttpContext.Current.Items["RequestInfo"] = logContent.ToString();
            }
            catch { }

            //注册自定义的ResponseFilter
            HttpHelper.RegisterToCaptureResponse(HttpContext.Current.Response);
        }

        protected void Application_EndRequest(object sender, EventArgs e)
        {
            var response = HttpContext.Current.Response;
            var logContent = new StringBuilder(2 * 1024); //default capacity 2kb
            try
            {
                var requestInfo = HttpContext.Current.Items["RequestInfo"] as string;
                logContent.AppendLine(requestInfo ?? string.Empty);

                if (null != response)
                {
                    logContent.Append("Response = ");

                    var sResponseTime = "UTC " + DateTime.UtcNow.ToString(TIME_FORMAT);
                    var responseJson = HttpHelper.GetResponseJson(response, sResponseTime);
                    var formattedResponseJson = JsonHelper.FormatJson(responseJson);
                    logContent.Append(formattedResponseJson);
                }

                var log = Server.MapPath("~") + "Access_" + DateTime.UtcNow.ToString(TIME_FILE_FORMAT) + ".log";
                File.WriteAllText(log, logContent.ToString());
            }
            catch { }
        }
    }
}
